<?php

namespace app\modules\controllers;

use app\models\Category;
use app\modules\models\Admin;
use Symfony\Component\Yaml\Tests\A;
use yii\data\Pagination;
use yii\web\Controller;
use Yii;

/**
 * Default controller for the `admin` module
 */
class CategoryController extends Controller
{

    public function actionList(){
        $this->layout = 'layout1';
        $model = new Category();
        $data = $model->getData();
        $cates = $model->getTree($data);
        $cates = $model->setPrefix($cates);

        return $this->render("cates",['cates' => $cates]);
    }

    public function actionAdd(){

        $this->layout = "layout1";
        $model = new Category;
        $list = $model->getOptions();

        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            if ($model->add($post)){
                Yii::$app->session->setFlash('info', '添加类型成功');
            }
        }
        return $this->render("add", ['list' => $list, 'model' => $model]);
    }

    public function actionMod(){
        $id = Yii::$app->request->get('cateid');
        $this->layout = "layout1";
        $model = Category::find()->where('cateid=:id', [':id' => $id])->one();
        $list = $model->getOptions();
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            if ($model->load($post) && $model->save()){
                Yii::$app->session->setFlash('info', '修改成功');
            }
        }
        return $this->render("add", ['list' => $list, 'model' => $model]);

    }

    public function actionDel(){
        try {

            $id = Yii::$app->request->get('cateid');

            if (empty($id)) {
                throw new \Exception('参数错误');
            }

            $data = Category::find()->where('parentid=:pid', [':pid' => $id])->one();

            if ($data) {
                throw new \Exception('该分类下有子类');
            }
            if (!Category::deleteAll('cateid = :id', [':id' => $id])){
                throw new \Exception('删除失败');

            }
        }catch (\Exception $e){
            Yii::$app->session->setFlash('info', $e->getMessage());
        }
        return $this->redirect(['category/list']);
    }

}
